package com.kele.shiro.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



@Configuration
public class ShrioConfig {


	@Bean
	public ShiroFilterChainDefinition shiroFilterChainDefinition() {
		DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();

		// 免登录url配置，anon为shiro提供的filter名称
		chainDefinition.addPathDefinition("/user/login", "anon");
		chainDefinition.addPathDefinition("/user/register", "anon");
		chainDefinition.addPathDefinition("/register.html", "anon");
		chainDefinition.addPathDefinition("/favicon.ico", "anon");
		chainDefinition.addPathDefinition("/error", "anon");

		// cookie免登录可以直接访问的资源url
		chainDefinition.addPathDefinition("/home.html", "user");

		// all other paths require a logged in user
		chainDefinition.addPathDefinition("/**", "authc");
		return chainDefinition;
	}

	@Bean
	public Realm customRealm(){
		CustomRealm customRealm=new CustomRealm( );

		//密码匹配器对象
		HashedCredentialsMatcher hashedCredentialsMatcher=new HashedCredentialsMatcher( );

		hashedCredentialsMatcher.setHashAlgorithmName( "md5" );;

		hashedCredentialsMatcher.setHashIterations( 1024 );

		customRealm.setCredentialsMatcher( hashedCredentialsMatcher );

		// 整合缓存配置
		customRealm.setCacheManager(new EhCacheManager());
		// 开启缓存
		customRealm.setCachingEnabled(true);
		// 开启身份认证缓存
		customRealm.setAuthenticationCachingEnabled(true);
		// 开启授权数据缓存
		customRealm.setAuthorizationCachingEnabled(true);

		return customRealm;
	}

}
